import React, {useEffect, useState} from 'react';
import {Empty, Progress, Pagination} from 'antd';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import DrilingTable from '~/page/FineBi/common/DrilingTable';
import CommonCard from '~/page/FineBi/common/CommonCard';
import {queryValues} from '~/service/refundReport';
import {parsePercent, numberHandle, strToNumber} from '~/utils/number';
import {CODE_7001} from '~/service/http';
import {buildTip} from './common';

import './index.styl';
// 需要隐藏的列 [id, type]
const hidenColumnsConfig = [
    ['DepartmentDimensionReport_PartTen_can_renewal_num_sum_late_1', 2],
    ['DepartmentDimensionReport_PartTen_can_renewal_num_sum_late_2', 2],
    ['DepartmentDimensionReport_PartTen_total_renewal_num_sum_late_1', 3],
    ['DepartmentDimensionReport_PartTen_total_renewal_num_sum_late_2', 3],
    ['DepartmentDimensionReport_PartTen_target_total_renewal_num_sum_late_1', 3],
    ['DepartmentDimensionReport_PartTen_target_total_renewal_num_sum_late_2', 3],
    ['DepartmentDimensionReport_PartTen_comprehensive_target_renewal_num_sum_late_1', 3],
    ['DepartmentDimensionReport_PartTen_comprehensive_target_renewal_num_sum_late_2', 3],
    ['DepartmentDimensionReport_PartTen_target_completion_renewal_num_sum_late_1', 3],
    ['DepartmentDimensionReport_PartTen_target_completion_renewal_num_sum_late_2', 3],
    ['DepartmentDimensionReport_PartTen_target_renewal_num_sum_late_1', 3],
    ['DepartmentDimensionReport_PartTen_target_renewal_num_sum_late_2', 3],
    ['DepartmentDimensionReport_PartTen_renewal_num_sum_late_1', 3],
    ['DepartmentDimensionReport_PartTen_renewal_num_sum_late_2', 3],
];

function DTable(props) {
    // type string 区别大组，小组
    const {
        dimensionAndValues,
        unitId,
        dId: dashBoardId,
        userRoundValue
    } = props;

    const [data, setData] = useState({});
    const [loading, setLoading] = useState(false);
    const [excelDrilingList, setExcelDrilingList] = useState([]);
    const [total, setTotal] = useState();
    const [pageNum, setPageNum] = useState(1);
    const [pageSize, setPageSize] = useState(20);
    const [title, setTitle] = useState('');

    const getColumnValue = (value, text) => {
        switch (text) {
            case '可续人数-整体':
            case '可续人数-新学员':
            case '可续人数-老学员':
            case '可续人数-插1学员':
            case '可续人数-插2学员':
                return (
                    <span className="normal-col">
                        {strToNumber(value)}
                    </span>
                );
            case '综续目标-整体':
            case '综续目标-新学员':
            case '综续目标-老学员':
            case '综续目标-插1学员':
            case '综续目标-插2学员':
            case '纯续目标-整体':
            case '纯续目标-新学员':
            case '纯续目标-老学员':
            case '纯续目标-插1学员':
            case '纯续目标-插2学员':
            case '综合续班率-整体':
            case '综合续班率-新学员':
            case '综合续班率-老学员':
            case '综合续班率-插1学员':
            case '综合续班率-插2学员':
            case '综合续班率-今日新增':
            case '纯续班率-整体':
            case '纯续班率-新学员':
            case '纯续班率-老学员':
            case '纯续班率-插1学员':
            case '纯续班率-插2学员':
            case '扩科率':
            case '转介绍率':
                return (
                    <span className="normal-col">
                        {parsePercent(value, 2)}
                    </span>
                );
            case '纯续目标达成率-整体':
            case '纯续目标达成率-新学员':
            case '纯续目标达成率-老学员':
            case '纯续目标达成率-插1学员':
            case '纯续目标达成率-插2学员':
            case '综续目标达成率-整体':
            case '综续目标达成率-新学员':
            case '综续目标达成率-老学员':
            case '综续目标达成率-插1学员':
            case '综续目标达成率-插2学员':
                return (
                    <div className="general-custom-col">
                        <span className="custom-col-value">
                            {parsePercent(value, 2)}
                        </span>
                        <Progress
                            showInfo={false}
                            strokeLinecap="square"
                            strokeWidth={30}
                            strokeColor="#1890ff"
                            percent={numberHandle(value * 100, 1)}
                        />
                    </div>
                );
            default:
                return (
                    <span className="normal-col">
                        {value}
                    </span>
                );
        }
    };

    const search = () => {
        const dashBoard = [
            {
                dashBoardName: dashBoardId,
                dashBoardId
            }
        ];
        const hiddenColumns = userRoundValue === 1
            ? hidenColumnsConfig.map(([fieldId, fieldType]) => ({
                fieldId,
                fieldType
            }))
            : [];
        const param = {
            excelDrilingList,
            dimensionAndValues,
            dashBoardList: dashBoard,
            pager: {
                pageNum,
                pageSize
            },
            hiddenColumns
        };
        setLoading(true);
        queryValues(param).then(res => {
            if (res.code === 0) {
                const resultData = res?.data[dashBoardId] || null;
                if (resultData) {
                    const dataRes = resultData[unitId] || {};
                    dataRes?.columns?.splice(1, 0, {text: 'rank1', dId: 'rank1', title: buildTip('主讲排名')});
                    const newColumns = dataRes?.columns?.map((item, index) => ({
                        customRender: value => getColumnValue(value, item.text),
                        props: {
                            className: 'table-col',
                            fixed: index < 3 && 'left',
                            width: index < 3 ? 120 : 100
                        },
                        ...item
                    }));
                    dataRes.columns = newColumns || [];

                    // const detail = buildDetailList(result);
                    setData(dataRes);
                    setTotal(res?.pager?.count);
                    setTitle(dataRes?.unitName);
                }
                else {
                    setData({});
                    setTotal(0);
                }
            }
        })
            .finally(code => {
                // 后端限流，啥也不操作
                if (code === CODE_7001) {
                    // return;
                }
                setLoading(false);
            });
    };

    const handleUpdateData = params => {
        const {drilingList, record, index, column, values, handleType} = params;
        let newExcelDrilingList = [];
        if (handleType === 'close') {
            newExcelDrilingList = excelDrilingList.concat([drilingList]);
        }
        else {
            newExcelDrilingList = excelDrilingList.filter(item => item.every(child => child.value !== record[column]));
        }
        setExcelDrilingList(newExcelDrilingList);
    };

    useEffect(() => {
        search();
    }, [excelDrilingList, pageNum, pageSize]);

    useEffect(() => {
        setPageNum(1);
        setExcelDrilingList([]);
    }, [dimensionAndValues]);

    const pagerChange = (page, pageSize) => {
        setPageNum(page);
    };

    return (
        <CommonCard
            title={title}
            showBtn={false}
            loading={loading}
            content={(
                <div className="dynamicTable-department">
                    {
                        data?.columns?.length
                            ? (
                                <>
                                    <DrilingTable
                                        dataSource={data}
                                        tableProps={{scroll: {y: 700}}}
                                        onUdateData={handleUpdateData}
                                    />
                                    <Pagination
                                        className="dtPager"
                                        size="small"
                                        total={total}
                                        current={pageNum}
                                        defaultPageSize={pageSize}
                                        onChange={pagerChange}
                                        showSizeChanger={false}
                                    />
                                </>
                            )
                            : <Empty />
                    }
                </div>
            )}
        />
    );
}

export default connect(s => s)(withRouter(DTable));
